#!/usr/bin/env node

// 批量添加单词工具
const fs = require('fs');

// 词库文件路径
const LEXICON_FILES = {
  'cet4': './cet4-words-100.json',
  'cet6': './cet6-words-100.json',
  'toefl': './toefl-words-100.json'
};

// 加载词库数据
function loadLexicon(set) {
  try {
    const data = fs.readFileSync(LEXICON_FILES[set], 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.error(`加载词库 ${set} 失败:`, error.message);
    return [];
  }
}

// 保存词库数据
function saveLexicon(set, data) {
  try {
    fs.writeFileSync(LEXICON_FILES[set], JSON.stringify(data, null, 2));
    console.log(`✅ 词库 ${set} 保存成功！`);
    return true;
  } catch (error) {
    console.error(`保存词库 ${set} 失败:`, error.message);
    return false;
  }
}

// 获取下一个ID
function getNextId(words) {
  return words.reduce((max, word) => Math.max(max, word.id || 0), 0) + 1;
}

// 批量添加单词
function batchAddWords(set, wordsData) {
  const words = loadLexicon(set);
  let addedCount = 0;
  let skippedCount = 0;
  
  wordsData.forEach(wordData => {
    // 检查单词是否已存在
    const exists = words.find(w => w.word.toLowerCase() === wordData.word.toLowerCase());
    if (exists) {
      console.log(`⚠️  单词 "${wordData.word}" 已存在，跳过`);
      skippedCount++;
      return;
    }
    
    // 添加新单词
    const newWord = {
      id: getNextId(words),
      ...wordData,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    words.push(newWord);
    addedCount++;
    console.log(`✅ 添加单词: ${wordData.word}`);
  });
  
  // 保存到文件
  if (saveLexicon(set, words)) {
    console.log(`\n📊 批量添加完成:`);
    console.log(`   - 成功添加: ${addedCount} 个单词`);
    console.log(`   - 跳过重复: ${skippedCount} 个单词`);
    console.log(`   - ${set.toUpperCase()} 词库现在有 ${words.length} 个单词`);
    return true;
  }
  
  return false;
}

// 示例用法
function showExample() {
  console.log('📚 批量添加单词示例:');
  console.log('='.repeat(50));
  
  const exampleWords = [
    {
      word: 'example',
      phonetic: '/ɪɡˈzæmpəl/',
      meaning: '例子；榜样',
      partOfSpeech: 'n.',
      difficulty: 2,
      frequency: 4,
      example: 'This is an example sentence.',
      exampleMeaning: '这是一个例句。',
      synonyms: ['instance', 'sample'],
      antonyms: ['exception'],
      tags: ['基础词汇', '常用词']
    },
    {
      word: 'demonstrate',
      phonetic: '/ˈdemənstreɪt/',
      meaning: '证明；演示',
      partOfSpeech: 'v.',
      difficulty: 3,
      frequency: 3,
      example: 'Please demonstrate how it works.',
      exampleMeaning: '请演示它是如何工作的。',
      synonyms: ['show', 'prove'],
      antonyms: ['hide', 'conceal'],
      tags: ['学术词汇', '常用动词']
    }
  ];
  
  console.log('示例单词数据:');
  console.log(JSON.stringify(exampleWords, null, 2));
  
  console.log('\n使用方法:');
  console.log('1. 修改下面的 wordsToAdd 数组');
  console.log('2. 设置正确的 set 参数');
  console.log('3. 运行脚本');
}

// 主函数
function main() {
  console.log('🎯 快背单词 - 批量添加单词工具');
  console.log('='.repeat(50));
  
  // 显示当前统计
  console.log('\n📚 当前词库统计:');
  console.log('='.repeat(40));
  Object.keys(LEXICON_FILES).forEach(set => {
    const words = loadLexicon(set);
    console.log(`${set.toUpperCase()}: ${words.length} 个单词`);
  });
  console.log('='.repeat(40));
  
  // 要添加的单词数据
  const wordsToAdd = [
    // 在这里添加您要添加的单词
    // 格式如下：
    /*
    {
      word: '单词',
      phonetic: '/音标/',
      meaning: '释义',
      partOfSpeech: '词性',
      difficulty: 难度(1-5),
      frequency: 频率(1-5),
      example: '例句',
      exampleMeaning: '例句翻译',
      synonyms: ['同义词1', '同义词2'],
      antonyms: ['反义词1', '反义词2'],
      tags: ['标签1', '标签2']
    }
    */
  ];
  
  // 选择词库
  const set = 'cet4'; // 修改为 'cet4', 'cet6', 或 'toefl'
  
  if (wordsToAdd.length === 0) {
    console.log('\n⚠️  没有要添加的单词！');
    showExample();
    return;
  }
  
  console.log(`\n📝 准备向 ${set.toUpperCase()} 词库添加 ${wordsToAdd.length} 个单词:`);
  wordsToAdd.forEach((word, index) => {
    console.log(`${index + 1}. ${word.word} - ${word.meaning}`);
  });
  
  // 执行批量添加
  batchAddWords(set, wordsToAdd);
}

// 启动程序
if (require.main === module) {
  main();
}

module.exports = { batchAddWords, loadLexicon, saveLexicon };
